<template>
  <lay-layer
    v-model="visible"
    :title="dialogTitle"
    :area="['800px', '600px']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="user-dialog-content">
      <lay-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :disabled="mode === 'view'"
        label-width="100px"
      >
        <lay-row :space="16">
          <lay-col :md="12">
            <lay-form-item label="用户名" prop="username">
              <lay-input v-model="formData.username" placeholder="请输入用户名" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="邮箱" prop="email">
              <lay-input v-model="formData.email" placeholder="请输入邮箱" />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16" v-if="mode === 'create'">
          <lay-col :md="12">
            <lay-form-item label="密码" prop="password">
              <lay-input
                v-model="formData.password"
                type="password"
                placeholder="请输入密码"
              />
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="确认密码" prop="confirmPassword">
              <lay-input
                v-model="formData.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
              />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16">
          <lay-col :md="12">
            <lay-form-item label="手机号" prop="phone">
              <lay-input v-model="formData.phone" placeholder="请输入手机号" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="昵称" prop="nickname">
              <lay-input v-model="formData.nickname" placeholder="请输入昵称" />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16">
          <lay-col :md="12">
            <lay-form-item label="性别" prop="gender">
              <lay-select v-model="formData.gender" placeholder="请选择性别">
                <lay-select-option :value="0">未知</lay-select-option>
                <lay-select-option :value="1">男</lay-select-option>
                <lay-select-option :value="2">女</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="生日" prop="birthday">
              <lay-input
                v-model="formData.birthday"
                placeholder="请选择生日"
                type="date"
                :readonly="false"
              />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16" v-if="mode !== 'create'">
          <lay-col :md="12">
            <lay-form-item label="状态" prop="status">
              <lay-select v-model="formData.status" placeholder="请选择状态">
                <lay-select-option :value="1">正常</lay-select-option>
                <lay-select-option :value="0">禁用</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="用户等级" prop="levelId">
              <lay-input-number
                v-model="formData.levelId"
                :min="1"
                :max="10"
                placeholder="用户等级"
              />
            </lay-form-item>
          </lay-col>
        </lay-row>

        <lay-row :space="16" v-if="mode !== 'create'">
          <lay-col :md="12">
            <lay-form-item label="积分" prop="points">
              <lay-input-number
                v-model="formData.points"
                :min="0"
                placeholder="用户积分"
              />
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item label="余额" prop="balance">
              <lay-input-number
                v-model="formData.balance"
                :min="0"
                :step="0.01"
                placeholder="账户余额"
              />
            </lay-form-item>
          </lay-col>
        </lay-row>



        <!-- 查看模式下显示额外信息 -->
        <template v-if="mode === 'view' && userData">
          <lay-line style="margin: 20px 0;" />
          <div class="section-title">账户信息</div>
          <lay-row :space="16">
            <lay-col :md="12">
              <lay-form-item label="注册时间">
                <lay-input :model-value="formatDate(userData.createdAt)" readonly />
              </lay-form-item>
            </lay-col>
            <lay-col :md="12">
              <lay-form-item label="最后登录">
                <lay-input :model-value="formatDate(userData.lastLoginAt)" readonly />
              </lay-form-item>
            </lay-col>
          </lay-row>
          <lay-row :space="16">
            <lay-col :md="24">
              <lay-form-item label="用户地址">
                <lay-button type="primary" @click="handleManageAddress">
                  管理地址
                </lay-button>
              </lay-form-item>
            </lay-col>
          </lay-row>
        </template>
      </lay-form>

      <div class="dialog-footer">
        <lay-button @click="handleClose">取消</lay-button>
        <lay-button 
          v-if="mode !== 'view'" 
          type="primary" 
          :loading="loading"
          @click="handleSubmit"
        >
          {{ mode === 'create' ? '创建' : '保存' }}
        </lay-button>
      </div>
    </div>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { layer } from '@layui/layui-vue'
import { UserApi } from '../../../api/module/user'
import type { User, CreateUserRequest, UpdateUserRequest } from '../../../types/user'

// Props
interface Props {
  modelValue: boolean
  userData?: User | null
  mode: 'view' | 'create' | 'edit'
}

const props = withDefaults(defineProps<Props>(), {
  userData: null,
  mode: 'view'
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
  'manage-address': [userId: number]
}>()

// 响应式数据
const loading = ref(false)
const formRef = ref()

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单数据
const formData = reactive<CreateUserRequest & UpdateUserRequest & { confirmPassword?: string }>({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  phone: '',
  nickname: '',
  gender: 0,
  birthday: null,
  status: 1,
  levelId: 1,
  points: 0,
  balance: 0
})

// 计算属性
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'create': return '新增用户'
    case 'edit': return '编辑用户'
    case 'view': return '用户详情'
    default: return ''
  }
})

// 表单验证规则
const formRules = computed(() => {
  const rules: any = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
  }

  if (props.mode === 'create') {
    rules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
    rules.confirmPassword = [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value !== formData.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  return rules
})

// 监听用户数据变化
watch(
  () => props.userData,
  (newUser) => {
    if (newUser) {
      Object.assign(formData, {
        username: newUser.username,
        email: newUser.email,
        password: '',
        confirmPassword: '',
        phone: newUser.phone || '',
        nickname: newUser.nickname || '',
        gender: newUser.gender,
        birthday: newUser.birthday || null,
        status: newUser.status,
        levelId: newUser.levelId,
        points: newUser.points,
        balance: newUser.balance
      })
    } else {
      // 重置表单
      Object.assign(formData, {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        phone: '',
        nickname: '',
        gender: 0,
        birthday: null,
        status: 1,
        levelId: 1,
        points: 0,
        balance: 0
      })
    }
  },
  { immediate: true }
)

// 方法
const handleClose = () => {
  emit('update:modelValue', false)
  if (formRef.value) {
    formRef.value.reset()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    if (props.mode === 'create') {
      const { confirmPassword, ...createData } = formData
      await UserApi.createUser(createData as CreateUserRequest)
      layer.msg('用户创建成功', { icon: 1 })
    } else if (props.mode === 'edit' && props.userData) {
      const { password, confirmPassword, ...updateData } = formData
      await UserApi.updateUser(props.userData.id, updateData as UpdateUserRequest)
      layer.msg('用户更新成功', { icon: 1 })
    }

    emit('success')
    handleClose()
  } catch (error) {
    layer.msg(props.mode === 'create' ? '创建失败' : '更新失败', { icon: 2 })
    console.error('提交失败:', error)
  } finally {
    loading.value = false
  }
}

const handleManageAddress = () => {
  if (props.userData) {
    emit('manage-address', props.userData.id)
  }
}



// 工具方法
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.user-dialog-content {
  padding: 20px;
  max-height: 500px;
  overflow-y: auto;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 4px solid #1890ff;
}



.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

.dialog-footer .lay-button {
  margin-left: 8px;
}

.dialog-footer .lay-button:first-child {
  margin-left: 0;
}
</style>